package cutCriteria;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import neural.Individual;

import core.Problem;

public class StructureCutCriteria implements CutCriteria {

	private double percentage;
	private double converge = 0.001;

	public StructureCutCriteria(double percentage) {
		this.percentage = percentage;
	}

	@Override
	public Boolean shouldFinish(Problem problem) {

		int counter = 1;
		List<Double> aptitudes = new ArrayList<Double>();

		for (Individual d : problem.getIndividuals()) {
			aptitudes.add(d.getFitness());
		}

		Collections.sort(aptitudes, new Comparator<Double>() {

			@Override
			public int compare(Double o1, Double o2) {

				return (int) Math.ceil(o2 - o1);
			}

		});

		Iterator<Double> iter = aptitudes.iterator();

		double max = iter.next();

		while (iter.hasNext()) {
			double d = iter.next();

			if (max - d < converge) {
				counter++;
			} else {
				break; // aptitudes is ordered.
			}
		}

		return counter * 100 / ((double) aptitudes.size()) >= percentage;

	}

}
